package com.cefa.finance.config;

import com.cefa.finance.dao.AccountRepository;
import com.cefa.finance.model.Account;
import com.cefa.finance.service.BlockChainService;
import com.cefa.finance.utils.MD5Generator;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Component
public class AdminApplicationRunner {
    private static final Logger logger = LoggerFactory.getLogger(AdminApplicationRunner.class);

    @Autowired
    private AccountRepository accountRepository;

    @Autowired
    private ConstantProperties constantProperties;

    @Autowired
    private BlockChainService blockChainService;

    @Transactional("transactionManagerPrimary")
    public void run() throws Exception {
        logger.info("---------------初始化数据操作---------------");

        String initPassword = constantProperties.initPassword;
        String initphone = constantProperties.initphone;
        String initUserName = constantProperties.initUserName;
        String initUserAccount = constantProperties.initUserAccount;

        Account admin = accountRepository.findByUserAccountAndSuperUser("admin", true);

        if (admin == null) {
            Account account = new Account();
            account.setPassword(MD5Generator.generatorMD5(initPassword));
            account.setPhone(initphone);
            account.setUserAccount(initUserAccount);
            account.setTenantryName(initUserName);
            account.setSuperUser(true);
            account.setRegisterDate(new Date());

            Account wallet = null;
            try {
                wallet = blockChainService.getWallet();
            } catch (Exception e) {
                e.printStackTrace();
            }

            if (wallet != null && wallet.getPrikey() != null && wallet.getAddress() != null) {
                account.setPrikey(wallet.getPrikey());
                account.setAddress(wallet.getAddress());
            }
            accountRepository.save(account);
        } else {
            if (admin.getPrikey() == null && admin.getAddress() == null) {
                Account wallet = null;
                try {
                    wallet = blockChainService.getWallet();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                if (wallet != null && wallet.getPrikey() != null && wallet.getAddress() != null) {
                    admin.setPrikey(wallet.getPrikey());
                    admin.setAddress(wallet.getAddress());
                    accountRepository.save(admin);
                }
            }
        }
    }
}
